import React, { useState, useEffect } from 'react';
import {
  SearchOutlined,
  PlusSquareOutlined, EditOutlined, ReloadOutlined, UnorderedListOutlined, ToolOutlined, FileExcelOutlined, PrinterOutlined
} from '@ant-design/icons';
import { Select, Button, Spin, Tabs, Space, Popconfirm, Input, DatePicker, List, Tooltip } from 'antd';
import {
  openNotification_util, fetchsync_util,
  dealnullorundenfined,
  convertISODateTimeToYYYYMMDDHHMMSS,
  convertISODateTimeToYYYYMMDD,
  selectedRows_to_printColumn,
  replace_value_util
} from '../util/util.js'
var storage = window.localStorage;
const { Option } = Select;
import { getLodop } from './LodopFuncs.js';
const { RangePicker } = DatePicker;


import { use_httz_initcolmun, use_htmb_print_colmun } from './use_htzx_config.js';
import useStore from '../../useStore.js'
import { dropByCacheKey } from 'react-router-cache-route';
import ResizableTable from '../newmes/Resize_table_hook.js';
import { useLatest } from 'ahooks';
import Sortable_new from '../newmes/sortable_new.js';

const ListItem = (props) => {
  return (
    <>
      <List
        dataSource={props.dataSource}
        renderItem={(item, index) => (

          <div style={{
            width: "19.4vw", height: "10vw", position: "relative", margin: "0.5vw", display: "inline-block",
            textAlign: "center", boxShadow: "0 4px 8px rgba(0,0,0,0.2)", borderRadius: "0.4vw",
          }} onDoubleClick={() => { props.handleEdit(item, "view") }}>
            <div style={{ width: "100%", height: "1vw", position: "relative", fontSize: "1.5vw", fontWeight: "800", display: "flex", marginTop: "0.5vw", fontFamily: "'微软雅黑',sans-serif" }}>
              <div style={{ width: "30%", height: "100%", position: "relative", color: "#3E8EE6", textAlign: "left", textIndent: "1rem", fontSize: "0.8rem" }}>{item.htzt}</div>
              <div style={{ width: "70%", height: "100%", position: "relative", color: "#a91f24", textAlign: "right", paddingRight: "1vw", fontSize: "0.8rem" }}>{item.htbh}</div>
            </div>

            <div style={{ width: "100%", height: "2vw", position: "relative", fontSize: "1rem", marginTop: "1vw", textAlign: "left", textIndent: "1rem", fontWeight: "700" }}>
              <Tooltip title={item.htmc}>
                <div style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                  {item.htmc}
                </div>
              </Tooltip>
            </div>
            <div style={{ width: "100%", height: "1vw", marginTop: "0.5vw", position: "relative", textAlign: "left", textIndent: "1vw", fontSize: "0.8vw", fontWeight: "700" }}>
              {item.yfqc}
            </div>
            <div style={{ width: "100%", height: "1vw", marginTop: "0.5vw", position: "relative", textAlign: "left", textIndent: "1vw", fontSize: "0.8vw", fontWeight: "700" }}>
              {item.htje} 元
            </div>
            <div style={{ width: "100%", height: "1vw", marginTop: "0.5vw", position: "relative", textAlign: "left", textIndent: "1vw", fontSize: "0.8vw", fontWeight: "700" }}>
              <div style={{ width: "50%", height: "100%", position: "absolute", left: "0", textAlign: "left", textIndent: "1vw", fontSize: "0.8vw", fontWeight: "500", color: "#888" }}>
                {item.qsrq} | {item.create_by}
              </div>
              <div style={{ width: "40%", height: "100%", position: "absolute", right: "1rem", textAlign: "right", textIndent: "1vw", fontSize: "0.8vw", fontWeight: "700" }}>

                <Button type="primary" size="small" onClick={() => { props.handleEdit(item, "edit") }}>跟进</Button>
              </div>
            </div>

          </div>

        )}
      />
      {/* <Pagination size="small" defaultCurrent={1} total={props.pagedata.totalnum} style={{ marginBottom: '2vw', marginTop: '2vw' }}
        onChange={props.onShowSizeChange} current={props.pagedata.current}

      /> */}
    </>
  )
}

const Httz_list = () => {
  const [selectedRows, setselectedRows] = useState([])
  const [selectedRowKeys, setselectedRowKeys] = useState([])
  const [isloading, setisloading] = useState(true)
  const [initSize, setinitSize] = useState() //table宽度大小
  const [ifshow, setifshow] = useState(true)
  const [listdata, setlistdata] = useState([])
  const [columnarr, setcolumnarr] = useState(use_httz_initcolmun)
  const [htmbmc, setHtmbmc] = useState("")
  const [zbpl, setZbpl] = useState("")
  const xmmcRef = useLatest(xmmc)
  const htztRef = useLatest(htzt)
  const [showtype, setshowtype] = useState(false)
  const { setnowroute, collapsed } = useStore();
  const [startDate, setStartDate] = useState(null);
  const [endDate, setEndDate] = useState(null);
  const [xmmc, setXmmc] = useState("")
  const [htzt, setHtzt] = useState("")
  const [currentPage, setCurrentPage] = useState(1);


  useEffect(() => {
    querylist()
    storage[`Pc_httz_list_${storage.userid}`] ? setcolumnarr(JSON.parse(storage[`Pc_httz_list_${storage.userid}`])) : setcolumnarr(columnarr)
    storage[`Pc_httz_list__initsize_${storage.userid}`] ? setinitSize(storage[`Pc_httz_list__initsize_${storage.userid}`]) : setinitSize(1)
  }, [])

  useEffect(() => { ifshow ? "" : setifshow(true) }, [ifshow])




  //路由跳转

  const querylist = async () => {
    setisloading(true)
    storage[`Pc_httz_list_${storage.userid}`] ? setcolumnarr(JSON.parse(storage[`Pc_httz_list_${storage.userid}`])) : setcolumnarr(columnarr)
    let rtdata = await fetchsync_util("/admin/htzx/httzlb", 'POST', { ksqr: startDate, jsrq: endDate, xmmc: xmmcRef.current, htzt: htztRef.current }, "json")
    // openNotification_util(rtdata.rtmessage)

    console.log("rtdata==================================", rtdata)
    rtdata.resultdata.forEach(element => {
      element.create_time = element.create_time ? convertISODateTimeToYYYYMMDDHHMMSS(element.create_time) : ""
      element.qsrq = element.qsrq ? convertISODateTimeToYYYYMMDD(element.qsrq) : ""

    });
    setlistdata(dealnullorundenfined(rtdata.resultdata))

    setselectedRowKeys([])
    setselectedRows([])
    setifshow(false)
    setisloading(false)
  }


  const changeShowType = () => {
    setshowtype(!showtype)
  }
  /**
   * 手动查询
   */
  const handleQuery = async () => {
    querylist()
  }
  /**
   * 新增
   */
  const handleadd = async () => {
    storage.pre_httz_item = JSON.stringify({ data: {}, type: "add" })
    dropByCacheKey('httz_form')
    setnowroute({ ...{ route: "/shipSRM/htzx/httz_form", title: "合同台账_新增" } })
  }
  /**
   * 编辑
   */
  const handleEdit = async (data, type) => {
    storage.pre_httz_item = JSON.stringify({ data, type })
    dropByCacheKey('httz_form')
    setnowroute({ ...{ route: "/shipSRM/htzx/httz_form", title: "合同台账_" + `${type == "edit" ? "编辑" : "查看"}` } })
  }
  /**
   * 打印
   */
  const handleprint = async () => {
    if (selectedRows.length == 0) {
      openNotification_util("请先选择数据再打印！")
      return
    }
    if (!selectedRows[0].htmbid) {
      openNotification_util("请先选择模板再打印！")
      return
    }
    //获取模板数据
    var rtdata = await fetchsync_util("/admin/htzx/query_htmb_byid", 'POST', { id: selectedRows[0].htmbid }, "json")
    //将selectedRows中的数据替换variables中的数据
    var variables = selectedRows_to_printColumn(selectedRows, use_htmb_print_colmun())
    //将模板数据中的${变量}替换为variables中的变量值
    var value = replace_value_util(rtdata.resultdata.formdata.mbnr, variables)
    console.log(value, "value");

    // var LODOP = getLodop();
    // if (LODOP) {
    //   LODOP.PRINT_INIT("打印任务名");
    //   LODOP.ADD_PRINT_HTM(0, 0, "100%", "100%", value)
    //   LODOP.PREVIEW()
    // }
    // else{
      const printContent = value;
      const iframe = document.createElement('iframe');
      iframe.setAttribute('style', 'position: absolute;height: 100vh; width: 100vw;');
      document.body.appendChild(iframe);
      const iframeDoc = iframe.contentWindow.document;
      // // 设置打印展示方式 - 横向展示
      // iframeDoc.write('<style media="print">@page { margin: 1cm 2cm 1cm 2cm;}</style>');
      // 向 iframe 中注入 printContent 样式
      iframeDoc.write(`<link href="./print.css" media="print" rel="stylesheet" />`);
      // 写入内容
      iframeDoc.write('<div style="width:100%">' + printContent + '</div>');
      setTimeout(function(){
        iframe.contentWindow?.print({
           printArea:[0,0,window.innerWidth*0.98,window.innerHeight*0.98]
        });
        document.body.removeChild(iframe);
      }, 50);
    // }
  }

  /**
   * 删除
   */
  const handleDelete = async (selectedRows) => {
    let rtdata = await fetchsync_util("/admin/htzx/delete_httz", 'POST', { selectedRows }, "json")
    openNotification_util(rtdata.rtmessage)
    querylist()
  }

  const TabPaneItem = (title, listdata, columnarr, key) => {
    return <Tabs.TabPane tab={<span>{title} <span style={{
      display: 'inline-block', padding: '0 6px', fontSize: '12px', lineHeight: '14px', backgroundColor: '#a91f24',
      color: 'white', borderRadius: '8px', marginLeft: '4px'
    }}>{listdata.length}</span></span>}
      key={key}>
      {isloading ?
        (<div style={{ width: "10%", height: "10%", position: "absolute", left: "50%", top: "49%", color: "#14d9cc" }}>
          <Spin /></div>)
        :
        (<ResizableTable tabledata={listdata} tablecolnum={columnarr}
          width={collapsed ? "94%" : "84%"}
          storageName={`Pc_httz_list_${storage.userid}`}
          czWidth={120}
          sfdoubleclick="false" ifhiddencchangeselecttype="true"
          selectedRows={selectedRows} selectedRowKeys={selectedRowKeys}
          showCz={{ showEdit: true, showDelete: true, showView: true }}
          handleEdit={(data) => handleEdit(data, "edit")}
          handleView={(data) => handleEdit(data, "view")}
          handleDelete={(data) => handleDelete(data)}
          defaultPageSize={10}
          bordered
          scroll={{ x: 1600 }}
          handleselectson={(selectedRows, selectedRowKeys) => {
            setselectedRows(selectedRows)
            setselectedRowKeys(selectedRowKeys)
          }}
        />)
      }
    </Tabs.TabPane>
  }

  const ListPaneItem = (title, datasorce, key) => {
    return <Tabs.TabPane tab={<span>{title} <span style={{
      display: 'inline-block', padding: '0 6px', fontSize: '12px', lineHeight: '14px', backgroundColor: '#a91f24',
      color: 'white', borderRadius: '8px', marginLeft: '4px'
    }}>{datasorce.length}</span></span>}
      key={key}>


      <div>
        <ListItem
          dataSource={datasorce.slice((currentPage - 1) * 12, currentPage * 12)}
          pagedata={{
            totalnum: datasorce.length,
            current: currentPage,
            pageSize: 12
          }}
          handleEdit={(data) => handleEdit(data, "edit")}
          handleView={(data) => handleEdit(data, "view")}
          onShowSizeChange={(page) => setCurrentPage(page)}
        />

        <div style={{ textAlign: 'right', marginTop: '20px', marginRight: "17vw" }}>
          <Space>
            <Button
              disabled={currentPage === 1}
              onClick={() => setCurrentPage(currentPage - 1)}
            >
              上一页
            </Button>
            {Array.from({ length: Math.ceil(datasorce.length / 12) }, (_, i) => i + 1)
              .filter(page => {
                const totalPages = Math.ceil(datasorce.length / 12);
                return page <= 5 || page === totalPages || page === currentPage;
              })
              .map((page, index, array) => {
                if (index > 0 && array[index] - array[index - 1] > 1) {
                  return [
                    <Button key={`ellipsis-${page}`} disabled>...</Button>,
                    <Button
                      key={page}
                      type={currentPage === page ? 'primary' : 'default'}
                      onClick={() => setCurrentPage(page)}
                    >
                      {page}
                    </Button>
                  ];
                }
                return (
                  <Button
                    key={page}
                    type={currentPage === page ? 'primary' : 'default'}
                    onClick={() => setCurrentPage(page)}
                  >
                    {page}
                  </Button>
                );
              })}
            <Button
              disabled={currentPage === Math.ceil(datasorce.length / 12)}
              onClick={() => setCurrentPage(currentPage + 1)}
            >
              下一页
            </Button>
          </Space>
        </div>
      </div>

    </Tabs.TabPane>
  }


  return (
    <div style={{
      height: "94%", backgroundColor: `#F1F1F1`, right: "1%", top: "4vh", overflow: "hidden",
      backgroundSize: "100% 100%", width: collapsed ? "94%" : "84%", position: "absolute", color: "white", fontSize: "0.8rem",
      paddingRight: "1%" // 新增右侧留白
    }}>



      <div style={{...styles.kshcontainer, paddingRight: "1vw"}}>
        <div style={{
          width: "99vw", height: "78vw", backgroundColor: "white", overflowX: "scroll", margin: "0.5vw",
          paddingLeft: "1vw"
        }}>

          <div style={styleobj.linestyleflex}>
            <ToolOutlined style={{ fontSize: "1rem", color: "#666666" }} />
            &nbsp;&nbsp;&nbsp;
            <span style={{ fontSize: "0.8rem", fontWeight: "500", color: "#666666" }}>工具栏</span>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <span style={{ fontSize: "0.7rem", fontWeight: "500" }}>签署日期&nbsp;&nbsp;</span>
            <RangePicker
              style={{ width: "280px" }}
              onChange={(dates) => {
                if (dates) {
                  setStartDate(dates[0]);
                  setEndDate(dates[1]);
                } else {
                  setStartDate(null);
                  setEndDate(null);
                }
              }}
            />  &nbsp; &nbsp;
            <span style={{ fontSize: "0.7rem", fontWeight: "500" }}>项目名称&nbsp;&nbsp;</span>
            <Input style={{ width: "120px" }} value={xmmc} onChange={(e) => setXmmc(e.target.value)} />  &nbsp; &nbsp;
            <span style={{ fontSize: "0.7rem", fontWeight: "500" }}>合同状态&nbsp;&nbsp;</span>
            <Select style={{ width: "120px" }} allowClear value={htzt} onChange={(value) => setHtzt(value)}>
              <Option value="新建">新建</Option>
              <Option value="生效中">生效中</Option>
              <Option value="已归档">已归档</Option>
              <Option value="意外终止">意外终止</Option>
            </Select>  &nbsp; &nbsp;
            &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "500" }}
              onClick={() => { isloading ? openNotification_util("请等待数据查询完成再操作！") : handleQuery() }}>
              <SearchOutlined />查 询</Button>
            &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "500" }}
              onClick={() => { setHtmbmc(""); setZbpl("") }}>
              <ReloadOutlined />重 置</Button>
            &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "500" }}
              onClick={changeShowType}>
              <UnorderedListOutlined />切换{showtype ? '卡片' : '列表'}</Button>
            &nbsp;<Button style={{ backgroundColor: "white", color: "white", fontWeight: "500", backgroundColor: "#a91f24" }}
              onClick={handleadd}>
              <PlusSquareOutlined />新 增</Button>
            &nbsp;<Button style={{ backgroundColor: "white", color: "white", fontWeight: "500", backgroundColor: "#a91f24" }}
              onClick={handleprint}>
              <PrinterOutlined />打 印</Button>
            {/* &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handleEdit}>
              <EditOutlined /> 编 辑 </Button> */}
            {/* &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handledelete}>
              <MinusSquareOutlined /> 删 除</Button> */}
          </div>

          <div style={{ width: "100%", height: "0.3vw", backgroundColor: "#F1F1F1" }}></div>
          {ifshow && <Sortable_new tableColnum={columnarr} handleTableColomn={(data) => { setcolumnarr(data); }}
            storageName={`Pc_httz_list_${storage.userid}`} style={{ position: 'absolute', right: '2vw', top: '1.2rem', fontSize: "1.5rem" }}
            initSize={initSize} handleInitSize={(data) => { setinitSize(data); storage[`Pc_httz_list__initsize_${storage.userid}`] = data; }}
          />}
          {showtype &&
            <Tabs defaultActiveKey="1" className='task-tabs' >

              {TabPaneItem("框架合同", listdata.filter(item => item.htlx == "框架合同"), columnarr, "1")}
              {TabPaneItem("固定价格合同", listdata.filter(item => item.htlx == "固定价格合同"), columnarr, "2")}
              {TabPaneItem("成本加成合同", listdata.filter(item => item.htlx == "成本加成合同"), columnarr, "3")}
              {TabPaneItem("单价合同", listdata.filter(item => item.htlx == "单价合同"), columnarr, "4")}
              {TabPaneItem("分期合同", listdata.filter(item => item.htlx == "分期合同"), columnarr, "5")}
              {TabPaneItem("服务合同", listdata.filter(item => item.htlx == "服务合同"), columnarr, "6")}
            </Tabs>
          }
          {!showtype &&
            <Tabs defaultActiveKey="1" className='task-tabs' >

              {ListPaneItem("框架合同", listdata.filter(item => item.htlx == "框架合同"), "1")}
              {ListPaneItem("固定价格合同", listdata.filter(item => item.htlx == "固定价格合同"), "2")}
              {ListPaneItem("成本加成合同", listdata.filter(item => item.htlx == "成本加成合同"), "3")}
              {ListPaneItem("单价合同", listdata.filter(item => item.htlx == "单价合同"), "4")}
              {ListPaneItem("分期合同", listdata.filter(item => item.htlx == "分期合同"), "5")}
              {ListPaneItem("服务合同", listdata.filter(item => item.htlx == "服务合同"), "6")}
            </Tabs>
          }


        </div>

      </div>
    </div>
  )
}


export default Httz_list


var styles = {
  maincontainer: {
    height: "100vh", backgroundColor: `#F1F1F1`,
    backgroundSize: "100% 100%", width: "100%", position: "absolute", left: "0", color: "white", fontSize: "0.8rem"
  },
  topcontainer: {
    width: "100%", height: "10vw", backgroundImage: "linear-gradient(to bottom,#e4e5eb , white)", paddingTop: "3vw",
    position: "relative", fontSize: "0.89rem", textIndent: "2rem", fontWeight: "800", color: "#a91f24", borderRadius: "0 0 15px 15px"
  },
  butdcstyle: { paddingLeft: "1.5vw", paddingRight: "1.5vw", height: "2vw", position: "absolute", right: "1%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },
  butmainstyle: { paddingLeft: "1.5vw", paddingRight: "1.5vw", height: "2vw", position: "absolute", right: "8%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },


  kshcontainer: {
    width: "100%", minHeight: "40vh", position: "absolute", top: "2vh", left: "0vw", backgroundColor: "#F1F1F1",
    color: "black"
  },
}
var styleobj = {
  linestyle: { height: "1.8rem", fontSize: "0.7rem", position: "relative", width: "100%", textIndent: "1rem" },
  linestylesmall: { height: "1.3rem", fontSize: "0.7rem", position: "relative", width: "100%", textIndent: "1rem" },

  linestyleflex: {
    height: "1.8rem", fontSize: "0.6rem", position: "relative", width: "96vw", marginLeft: "0.1%",
    display: "flex", justifyContent: "flex-start", alignItems: "center", marginBottom: "0.5rem", marginTop: "0.5rem"
  },
  linestyleflexitem: {
    height: "1.6rem", fontSize: "0.7rem", position: "relative", width: "23%", textIndent: "0.5rem",
    backgroundColor: "white", lineHeight: "1.6rem", fontSize: "0.75rem", fontWeight: "500", textAlign: "center"
  },
  linestyleflexitemleft: { backgroundColor: "#F0F0F0", position: "absolute", width: "35%", left: "0" },
  linestyleflexitemright: { backgroundColor: "white", position: "absolute", width: "64%", right: "0" },
  lineleft: { width: "100%", height: "100%", position: "absolute", left: "0%", textAlign: "left", lineHeight: "2rem", fontSize: "0.75rem", fontWeight: "700" },
}